package com.aca.market.service.impl;

import com.aca.market.entity.Item;
import com.aca.market.mapper.ItemMapper;
import com.aca.market.service.IItemService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author aca
 * @since 2020-11-13
 */

@Transactional
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    ItemMapper itemMapper;

    @Override
    //获取商品同类型的商品
    public List<Item> getItemListByType(Long type){
        return itemMapper.selectPage(new Page<Item>(1,4),
                new QueryWrapper<Item>().eq("type",type)).getRecords();
    }

    @Override
    //根据价格区间筛选商品 获取最大和最小价格区间 [min,max]
    public BigDecimal[] getLimitPrice(){
        List<BigDecimal> p = itemMapper.selectList(new QueryWrapper<Item>()
                .select("price_sell")
                .orderByAsc("price_sell"))
                .parallelStream()
                .map((item) -> item.getPriceSell())
                .collect(Collectors.toList());
        return new BigDecimal[]{p.get(0),p.get(p.size()-1)};
    }

    @Override
    public IPage<Item> selectItemPage(Page<Item> page, Wrapper<Item> queryWrapper){
        // 不进行 count sql 优化，解决 MP 无法自动优化 SQL 问题，这时候你需要自己查询 count 部分
        // page.setOptimizeCountSql(false);
        // 当 total 为小于 0 或者设置 setSearchCount(false) 分页插件不会进行 count 查询
        // 要点!! 分页返回的对象与传入的对象是同一个
        return itemMapper.selectPage(page,queryWrapper);
    }

    @Override
    //详情页的链接处理
    public List<String> getDetailImages(Long itemId){
        Item item = itemMapper.selectById(itemId);
        //处理多链接
        String urls = item.getImage();
        List<String> res;
        if (urls.indexOf(",")<0){
            res = new ArrayList<String>(){{add(urls);}};
        }else {
            String[] split = urls.split(",");
            res = Arrays.asList(split);
        }
//        System.out.println("===============URL " + res.toString());
        return res;
    }

}
